package com.young.exception;

import com.young.dto.ErrorInfo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

//@ControllerAdvice可以实现全局统一异常定义
//It is typically used to define @ExceptionHandler, @InitBinder, and @ModelAttribute methods that apply to all @RequestMapping methods.
//@RequestMapping用来将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上
//也就是说用@ControllerAdvice就可以实现对所有Controller中被@RequestMapping修饰的方法进行统一异常定义(或其他方面的增强)
@ControllerAdvice
public class GlobalExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error";

    //@ExceptionHandler用来定义函数针对的异常类型
    //不同的Exception定义不同的Handler，这里只是举一个例子
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        //将Exception对象和请求URL映射到error.html
        //mav.addObject("exception",e);
        mav.addObject("exception", e);
        mav.addObject("url",req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

    //用来处理自定义异常,这里用@ResponseBody，返回的json格式的自定义ErrorInfo对象，而不是页面
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
        ErrorInfo<String> r = new ErrorInfo<>();
        r.setMessage(e.getMessage());
        r.setCode(ErrorInfo.ERROR);
        r.setData("Some Data");
        r.setUrl(req.getRequestURL().toString());
        return r;
    }
}
